<?php

declare (strict_types=1);

namespace app\controller\auth;

use app\BaseController;
use think\facade\View;

class Admin extends BaseController
{

    public function initialize()
    {
        $model = new \app\model\auth\Admin();

        $this->childrenAdminIds = auth()->getChildrenAdminIds(true);
        $this->childrenGroupIds = auth()->getChildrenGroupIds(true);
        // 数组转换为数据集对象
        $groupList = $model->getAuthGroupList($this->childrenGroupIds);
        // 数据初始化
        tree()->init($groupList);
        $groupData = [];
        if (auth()->isSuperAdmin()) {
            $result = tree()->getTreeList(tree()->getTreeArray(0));
            foreach ($result as $v) {
                $groupData[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = auth()->getGroups();
            foreach ($groups as $n) {
                $childList = tree()->getTreeList(tree()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childList as $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[$n['name']] = $temp;
            }
            $groupData = $result;
        }

        return View::assign('groupData', $groupData);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $childrenAdminIds = auth()->getChildrenAdminIds(true);
            $model = new \app\model\auth\Admin();
            // 根据角色id获取角色名称
            $groupName = $model->getRoleName($childrenAdminIds);
            // 根据管理角色id，获取被分配的管理员id
            $authGroupList = $model->getAuthRoleList($childrenAdminIds);
            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = auth()->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[auth()->info('id')][$n['id']] = $n['name'];
            }
            // 获取页面查询条件
            [$where, $sort, $offset] = getBuildParams();
            // 操作记录数量和数据列表
            [$total, $list] = $model->getAdminList($childrenAdminIds, $where, $sort, $offset);
            // 循环数据插入角色名称
            foreach ($list as &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['role'] = implode(',', array_values($groups));
            }

            return json(result()->success(['count' => $total, 'rows' => $list]));
        }

        return View::fetch('index');
    }

    public function add()
    {
        return View::fetch('add');
    }
}